package com.jiuyuan;

import com.jiuyuan.entity.Employee;
import com.jiuyuan.entity.MailConstant;
import com.rabbitmq.client.Channel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.mail.MailProperties;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageHeaders;
import org.springframework.stereotype.Component;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import javax.mail.internet.MimeMessage;
import java.io.IOException;
import java.util.Date;

/**
 * @program: hrms
 * @description:
 * @author: Feng
 * @create: 2023-02-19 06:15
 **/

@Component
public class MailRecv {

    private static final Logger LOGGER = LoggerFactory.getLogger(MailRecv.class);
    @Autowired
    private JavaMailSender javaMailSender;
    @Autowired
    private MailProperties mailProperties;
    @Autowired
    private TemplateEngine templateEngine;
    @Autowired
    private RedisTemplate redisTemplate;

    @RabbitListener(queues = MailConstant.MAIL_QUEUE_NAME)
    public void handler(Message message, Channel channel) {
        //获取员工
        Employee employee = (Employee) message.getPayload();
        MessageHeaders headers = message.getHeaders();
        //序号
        String msgId = (String) headers.get("spring_returned_message_correlation");
        //标签，用于手动确认
        long tag = (long) headers.get(AmqpHeaders.DELIVERY_TAG);

        HashOperations hashOperations = redisTemplate.opsForHash();

        try {
            if(hashOperations.entries("mail_log").containsKey(msgId)){
                LOGGER.error("==================================>消息已被消费");
                channel.basicAck(tag,false);
                return;
            }
            MimeMessage mimeMessage = javaMailSender.createMimeMessage();
            MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMessage);
            //发件人
            messageHelper.setFrom(mailProperties.getUsername());
            //收件人
            messageHelper.setTo(employee.getEmail());
            //主题
            messageHelper.setSubject("入职欢迎邮件");
            //发送日期
            messageHelper.setSentDate(new Date());
            //邮件内容
            Context context = new Context();
            context.setVariable("name", employee.getName());
            context.setVariable("posName", employee.getPosition().getName());
            context.setVariable("jobLevelName", employee.getJoblevel().getName());
            context.setVariable("departmentName", employee.getDepartment().getName());
            String mail = templateEngine.process("mail", context);
            messageHelper.setText(mail, true);
            javaMailSender.send(mimeMessage);
            LOGGER.info("=》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》邮件发送成功!");
            hashOperations.put("mail_log",msgId,"ok");
            //确认
            channel.basicAck(tag,false);
        } catch (Exception e) {
            try {
                //错误，放回队列
                channel.basicNack(tag,false,true);
            } catch (IOException ex) {
                LOGGER.error("邮件发送失败======>{}", ex.getMessage());
            }
            LOGGER.error("邮件发送失败======>{}", e.getMessage());
        }
    }
}
